package com.example.demo.service;

import com.example.demo.dto.UserSigninDTO;
import com.example.demo.dto.UserSignupDTO;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void signupUser(UserSignupDTO userSignupDTO) {
        // 使用全参构造函数创建用户
        User user = new User();
        user.setUsername(userSignupDTO.getUsername());
        user.setPassword(userSignupDTO.getPassword());
        userRepository.save(user);
    }
    public void signinUser(UserSigninDTO userSigninDTO){
        Optional<User>userOptional = userRepository.findByUsername(userSigninDTO.getUsername());
        if (userOptional.isEmpty()){
            throw new UsernameNotFoundException("用户不存在");
        }
        User user = userOptional.get();

        if (!userSigninDTO.getPassword().equals(user.getPassword())){
            throw new BadCredentialsException("用户名或密码错误");
        }
    }
}